package com.sangmo.fts.process.receivable.service;

import com.sangmo.boot.framework.common.errors.ServiceException;
import com.sangmo.boot.framework.common.errors.StandardErrors;
import com.sangmo.boot.framework.common.security.meta.Access;
import com.sangmo.boot.framework.plugin.dataview.crud.service.BaseViewService;
import com.sangmo.boot.framework.plugin.dataview.data.IDataViewRepo;
import com.sangmo.fts.basic.model.Company;
import com.sangmo.fts.basic.service.CompanyService;
import com.sangmo.fts.common.authority.service.AuthorityEntityService;
import com.sangmo.fts.process.inventory.model.IfLoan;
import com.sangmo.fts.process.receivable.interfaces.RpfLoanCreation;
import com.sangmo.fts.process.receivable.model.RpfContract;
import com.sangmo.fts.process.receivable.model.RpfLoan;
import com.sangmo.fts.process.receivable.model.RpfWaybill;
import com.sangmo.fts.process.receivable.repo.RpfLoanRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
@Transactional
public class RpfLoanEntityService extends AuthorityEntityService<RpfLoan> {

    @Autowired
    private RpfLoanRepo rpfLoanRepo;

    @Autowired
    private RpfContractService rpfContractService;

    @Autowired
    private RpfWaybillService rpfWaybillService;

    @Autowired
    private CompanyService companyService;

    @Override
    protected IDataViewRepo<RpfLoan> getRepo() {
        return rpfLoanRepo;
    }

    @Override
    protected void onCreate(RpfLoan entity, Object bo) {
        super.onCreate(entity, bo);
        RpfLoanCreation creation = (RpfLoanCreation) bo;
        Company company = companyService.get(creation.getApplyId());
        BigDecimal rate = calcRate(company, creation.getDuration());
        entity.setRate(rate);
        entity.setBankId(company.getBankId());
        RpfContract contract = rpfContractService.get(creation.getContractId());
//        RpfWaybill waybill = rpfWaybillService.checkAndGetByContractId(entity.getTrainingId(),contract.getId());
        RpfWaybill waybill = rpfWaybillService.findAvailableByContractId(contract.getId(), entity.getTrainingId());
        entity.setWaybillId(waybill.getId());
        entity.setSubDebtor(contract.getBuyerId());
        entity.setContractAmount(waybill.getContractAmount());
    }

    private BigDecimal calcRate(Company company, String duration) {
        if (Company.CreditRating.D.equals(company.getCreditRating())) {
            throw new ServiceException(StandardErrors.CLIENT_ERROR.getStatus(), "error.company.creditRating.notEnough");
        }
        return Company.rateMap.get(company.getCreditRating()+"-"+duration);
    }

    public RpfLoan findByWaybillId(Long waybillId) {
        return rpfLoanRepo.findFirstByWaybillId(waybillId);
    }
}
